package kr.co.valueworks.fishing.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

import kr.co.valueworks.fishing.R;
import kr.co.valueworks.fishing.R.id;
import kr.co.valueworks.fishing.R.layout;
import kr.co.valueworks.fishing.model.FishingDBHelper;
import kr.co.valueworks.util.GoogleReverseGeocoder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Fishing extends BaseActivity {
	
	FishingDBHelper fishingDBHelpler;
	String TAG = Fishing.class.getName();
	public String pageType = "";
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fishing_list);
        
		AdView adView = (AdView)findViewById(R.id.adView);
	    AdRequest request = new AdRequest();
		adView.loadAd(request);
		
        Intent intent = getIntent();
        String type = intent.getStringExtra("type");
        pageType = type;
        String keyword = intent.getStringExtra("keyword");
        String area = intent.getStringExtra("area");
        String locality = intent.getStringExtra("locality");
        
        String fromLatitude = intent.getStringExtra("fromLatitude");
        String toLatitude = intent.getStringExtra("toLatitude");
        String fromLogitude = intent.getStringExtra("fromLogitude");
        String toLogitude = intent.getStringExtra("toLogitude");
		
        Log.d(TAG, "type : " + type);
        Log.d(TAG, "keyword : " + keyword);
        Log.d(TAG, "area : " + area);
        Log.d(TAG, "locality : " + locality);
        
		Cursor cursor = null;
		SQLiteDatabase db = null;
        try {
	        fishingDBHelpler = new FishingDBHelper(this);
			db = fishingDBHelpler.getReadableDatabase();
			String sql;
			
			if("search".equals(type))
			{
				if(area != null)
				{
					//sql = String.format("SELECT * FROM fishing WHERE area LIKE '%s%%' AND name LIKE '%%%s%%' ORDER BY name", area, keyword);
					sql = String.format("SELECT * FROM fishing WHERE area LIKE '%s%%' AND (name LIKE '%%%s%%' OR address LIKE '%%%s%%') AND status = 'Y' ORDER BY name", area, keyword, keyword);
				}
				else
				{
					//sql = String.format("SELECT * FROM fishing WHERE name LIKE '%%%s%%' ORDER BY name", keyword);
					sql = String.format("SELECT * FROM fishing WHERE (name LIKE '%%%s%%' OR address LIKE '%%%s%%') AND status = 'Y' ORDER BY name", keyword, keyword);
				}
			}
			else if("map".equals(type))
			{
				sql = String.format("SELECT * FROM fishing WHERE ( latitude BETWEEN '%s' AND '%s' ) AND ( longitude BETWEEN '%s' AND '%s' ) AND status = 'Y' ", 
						fromLatitude, toLatitude, fromLogitude, toLogitude);
			}
			else if("favorite".equals(type))
			{
				sql = String.format("SELECT * FROM fishing WHERE viewdate <> '' AND status = 'Y' ORDER BY viewdate DESC ");
			}			
			else
			{
				sql = String.format("SELECT * FROM fishing WHERE area LIKE '%s%%' AND locality = '%s' AND status = 'Y' ORDER BY name", area, locality);				
			}

			Log.d("Fishing", sql);
			cursor = db.rawQuery(sql, null);
			
			// When the activity is destroyed, all managed Cursors will be closed automatically.
			startManagingCursor(cursor);
			
			if(cursor.getCount() > 0)
			{
				FishingCursorAdapter Adapter = null;
				Adapter = new FishingCursorAdapter(this,cursor);		
				ListView list = (ListView)findViewById(R.id.fishingListView);
		        list.setAdapter(Adapter);			
			}
			else
			{
				if(!"favorite".equals(type))
				{
					Toast.makeText(this, R.string.noData, Toast.LENGTH_SHORT).show();
					finish();
				}
			}
        } catch (Exception e) {
        	e.getStackTrace();
        	Log.d(TAG, e.getMessage());
        } finally{
        	//cursor.close();
        	//db.close();
        }
        /*
        list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.v(parent.toString(), Integer.toString(position));
			}
		});
        */
		/*
		startManagingCursor(cursor);

		SimpleCursorAdapter Adapter = null;
		Adapter = new SimpleCursorAdapter(this, 
				android.R.layout.simple_list_item_2,
				cursor, new String[] { "name", "latitude" }, 
				new int[] { android.R.id.text1, android.R.id.text2});		
		ListView list = (ListView)findViewById(R.id.fishingListView);
        list.setAdapter(Adapter);
        */		

    }
}

class FishingCursorAdapter extends CursorAdapter {
	
	FishingDBHelper fishingDBHelpler;
	String TAG = Fishing.class.getName();
	Context mainContext;
	Cursor mCursor;
	
	public FishingCursorAdapter(Context context, Cursor c) {
		super(context, c);
		mainContext = context;
		mCursor = c;
	}

	protected void updateViewdate(final String fishingId) {
		// favorite 에 저장
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String curDate = formatter.format(cal.getTime());
		
        fishingDBHelpler = new FishingDBHelper(mainContext);
		SQLiteDatabase db = fishingDBHelpler.getWritableDatabase();
		db.execSQL("UPDATE fishing SET viewdate = '" + curDate + "' WHERE _id = " + fishingId + ";");
		db.close();
	}
	
	protected void deleteViewdate(final String fishingId) {
		// favorite 에 저장		
        fishingDBHelpler = new FishingDBHelper(mainContext);
		SQLiteDatabase db = fishingDBHelpler.getWritableDatabase();
		db.execSQL("UPDATE fishing SET viewdate = '' WHERE _id = " + fishingId + ";");
		db.close();
	}
	
	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(context);
        //View view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
        View view = inflater.inflate(R.layout.fishing_item, parent, false);
        return view;
        //return view.findViewById(R.id.fishingName);

	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		
		try{
			final String fishingId = cursor.getString(cursor.getColumnIndex("_id"));
			final String fishingName = cursor.getString(cursor.getColumnIndex("name"));
			final String latitude = cursor.getString(cursor.getColumnIndex("latitude"));
			final String longitude = cursor.getString(cursor.getColumnIndex("longitude"));
			final String address = cursor.getString(cursor.getColumnIndex("address"));
			final String locality = cursor.getString(cursor.getColumnIndex("locality"));
			
			((TextView)view.findViewById(R.id.fishingName)).setText(fishingName);
			((TextView)view.findViewById(R.id.address)).setText(address);
			
			view.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					updateViewdate(fishingId);
					
					Intent intent = new Intent(mainContext, FishingDetail.class);
		    		intent.putExtra("fishingId", fishingId);
		    		intent.putExtra("fishingName", fishingName);
		    		intent.putExtra("locality", locality);
					mainContext.startActivity(intent);
				}
			});
	
			
			
			Button btn = (Button)view.findViewById(R.id.mapBtn);
			btn.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View v) {
					
					/*
					String msg = "";
					double dLatitude = Double.parseDouble(latitude);
					double dLongitude = Double.parseDouble(longitude);
					
					GoogleReverseGeocoder grg = GoogleReverseGeocoder.getInstance(); 
					Location loc = new Location("");
					loc.setLatitude(dLatitude);
					loc.setLongitude(dLongitude);
					
					grg.startGeocodeAddress(loc);
					msg = grg._strAddress;
					
					Toast.makeText(mainContext, msg, Toast.LENGTH_SHORT).show();
					*/
					/*
					Locale.setDefault(Locale.KOREA);
					Geocoder geocoder = new Geocoder(mainContext.getApplicationContext());
					try {
						List<Address> addressList = geocoder.getFromLocation(dLatitude, dLongitude, 3);
						for(Address address : addressList) {
							msg += address.getCountryName();
							msg += address.getLocality();
						}
					} catch (Exception e) {
						Log.v("", e.getMessage());
					}
					
					Toast.makeText(mainContext, msg, Toast.LENGTH_SHORT).show();
					*/
					
					updateViewdate(fishingId);
					
					String pos = String.format("geo:%s,%s?z=16", latitude, longitude);
					Uri uri = Uri.parse(pos);
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					mainContext.startActivity(intent);
					/*
					Intent intent = new Intent(mainContext, FishingMap.class);
					intent.putExtra("latitude", latitude);
					intent.putExtra("longitude", longitude);
					mainContext.startActivity(intent);
					*/
									
				}
			});	
			if("favorite".equals(((Fishing)mainContext).pageType))
			{
				Button delBtn = (Button)view.findViewById(R.id.delBtn);
				delBtn.setVisibility(View.VISIBLE);
				delBtn.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						deleteViewdate(fishingId);
						mCursor.requery();
						notifyDataSetChanged();
					}
				});
			}
		}
		catch(Exception e)
		{
			Log.v(TAG,e.getMessage());
		}
	}	
}
